package com.shun.service

import com.shun.commons.ApiUtils
import com.shun.commons.exception.ApiException
import com.shun.entity.Company
import com.shun.entity.Machine
import com.shun.entity.TaskServer
import com.shun.entity.User
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.data.mongodb.core.query.Criteria
import org.springframework.data.mongodb.core.query.Query
import org.springframework.stereotype.Service
import java.util.*

/**
 * Created by rainbow on 2017/9/19.
 *一事专注，便是动人；一生坚守，便是深邃！
 */
@Service
class TaskServerService {

    @Autowired
    private lateinit var mongoTemplate: MongoTemplate

    @Autowired
    private lateinit var utils: ApiUtils

    fun create(params: Map<String, String>, user: User) {
        val tempCompany = mongoTemplate.findOne(Query.query(Criteria("name").`is`(params["name"])), Company::class.java) ?: throw ApiException("名称为${params["name"]}商户信息不存在")

        val tempServerUser = mongoTemplate.findOne(Query.query(Criteria("username").`is`(params["serverUser"])), User::class.java) ?: throw ApiException("用户名为${params["serverUser"]}的用户信息不存在")

        val tempMachine = mongoTemplate.findOne(Query.query(Criteria("machineCode").`is`(params["machineCode"])), Machine::class.java) ?: throw ApiException("设备编码为${params["machineCode"]}的设备信息不存在")

        val temp = TaskServer()
        temp.company = tempCompany
        temp.machine = tempMachine
        temp.question = params["question"]
        temp.serverUser = tempServerUser
        temp.status = 1
        temp.searchKey = build(temp)
        temp.user = user
        temp.time = params["time"]
        temp.createTime = Date()
        temp.type = params["type"]

        mongoTemplate.insert(temp)
    }

    fun list(params: Map<String, String>): Any {
        val criteria = Criteria()

        if (params["searchKey"].toString().isNotBlank()) criteria.and("searchKey").regex(params["searchKey"].toString())

        if (params["status"].toString().isNotBlank()) criteria.and("status").`in`(params["status"].toString().split(",").map(String::toInt))

        val query = Query.query(criteria)

        val page = if (params["page"] != null) params["page"].toString().toInt() else 0
        val size = if (params["size"] != null) params["size"].toString().toInt() else 10


        if (page > 0) {
            query.skip((page - 1) * size).limit(size)
        }

        val list = mongoTemplate.find(query, TaskServer::class.java)

        return if (page > 0) {
            mapOf(
                    "list" to list,
                    "page" to page,
                    "size" to size,
                    "total" to mongoTemplate.count(query, TaskServer::class.java)
            )
        } else {
            list
        }
    }

    fun build(t: TaskServer): String? {
        val keys = getSearchKeys(t)
        t.searchKey = if (keys.isNotEmpty()) {
            val first = utils.stringToPinyin(keys[0]!!, "first")
            val full = utils.stringToPinyin(keys[0]!!, "full")
            arrayOf(first.first(), first, full, *keys).distinct().joinToString(",")
        } else {
            ""
        }
        return t.searchKey
    }

    fun getSearchKeys(t: TaskServer) = arrayOf(t.company!!.name, t.serverUser!!.username)
}